package com.du.integration.server.controller;

import com.du.common.base.model.ResBean;
import com.du.integration.server.config.CustomMqttClient;
import com.du.integration.server.model.entity.MqttMsg;
import com.du.integration.server.model.entity.MsgParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * MQTT控制器，提供连接、断开、重连及消息发送等接口。
 * 通过注入的CustomMqttClient实现与MQTT服务器的交互。
 *
 * @author shuangdu
 * @date 2024/1/8
 */
@RestController
@RequestMapping("/mqtt")
@Slf4j
public class MqttController {

    @Resource
    private CustomMqttClient mqttClient;

    /**
     * 建立与MQTT服务器的连接。
     *
     * @return ResBean 操作结果，成功时返回ok
     */
    @GetMapping("/connect")
    public ResBean connect() {
        try {
            mqttClient.connect();
        } catch (Exception e) {
            log.info("出现异常!", e);
        }
        return ResBean.ok();
    }

    /**
     * 断开与MQTT服务器的连接。
     *
     * @return ResBean 操作结果，成功时返回ok
     */
    @GetMapping("/disconnect")
    public ResBean disconnect() {
        mqttClient.disconnect();
        return ResBean.ok();
    }

    /**
     * 重连MQTT服务器。
     *
     * @return ResBean 操作结果，成功时返回ok
     */
    @GetMapping("/reconnect")
    public ResBean reconnect() {
        mqttClient.reconnect();
        return ResBean.ok();
    }

    /**
     * 发送MQTT消息。
     *
     * @param param 消息参数，包括发送方、接收方和内容
     * @return ResBean 操作结果，成功时返回ok
     */
    @PostMapping("/sendMsg")
    public ResBean sendMsg(@RequestBody MsgParam param) {
        MqttMsg msg = new MqttMsg();
        msg.setTopic(String.format("testMqtt/%s/msg", param.getTo()));
        msg.setPayload(param.getContent());
        mqttClient.sendMsg(msg);
        return ResBean.ok();
    }

}
